package com.service.api;


import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.service.bean.company.Company;
import com.service.bean.device.Vehicle;
import com.service.bean.signal.GpsSignal;
import com.service.cache.CacheManager;
import com.service.db.DbManager;
import com.service.other.Logger;

public class BaiduApiGeoconv extends BaiduApiServer {
	private List<GpsSignal> beans = new ArrayList<GpsSignal>();
	
	public BaiduApiGeoconv(){
		
	}
	
	@Override
	public void run() {
		for (Vehicle vehicle : CacheManager.instance().getAllVehicle()) {
			Api_Geoconv(vehicle.company);
		}
	}
	
	@Override
	public void callBack(String json){
		String status = null;
		try {
			Pattern p = Pattern.compile("\"status\":\"?(?<status>\\w+)\"?");
			Matcher m = p.matcher(json);
			if (m.find()) {
				status = m.group("status");
				if("0".equals(status)){
					p = Pattern.compile("\"x\":(?<x>\\d+\\.\\d+),\"y\":(?<y>\\d+\\.\\d+)");
					m = p.matcher(json);
					int index = 0;
					while (m.find()) {
						GpsSignal b = beans.get(index);
						b.baiduLng = Double.parseDouble(m.group("x"));
						b.baiduLat = Double.parseDouble(m.group("y"));
						index++;
					}
					//Thread thread = new Thread(new BaiduApiLocation(this.beans));
					//thread.start();
				}
			}
		}catch(Exception e){
			Logger.err(e);
		}
	}
	
	private void Api_Geoconv(Company company){
		StringBuilder builder = new StringBuilder();
		builder.append("http://api.map.baidu.com/geoconv/v1/?");
		builder.append("ak=x2QVIn5dDgDC7wRZ6WGoQykb");
		builder.append("&from=1");
		builder.append("&to=5");
		builder.append("&output=json");
		builder.append("&coords=");
		beans = DbManager.instance().dbs.getMax100NoChangeGps(company);
		if(beans.size()>0){
			for(GpsSignal bean : beans){
				builder.append(String.valueOf(bean.lng));
				builder.append(",");
				builder.append(String.valueOf(bean.lat));
				builder.append(";");
			}
			String str = builder.toString();
			if(str.endsWith(";")){
				str = str.substring(0,str.lastIndexOf(";"));
			}
			try {
				HttpClient client = new HttpClient();
				client.doRequest(str,this);
			} catch (Exception e) {
				Logger.err(e);
			}
		}else{
			Logger.println("Baidu Api Geoconv Service : not point need change");
		}
	}
}
